<?php
namespace app\admin\controller;

use app\admin\inter_logic\CarLogic;
use app\admin\inter_logic\RefundLogic;
use app\inter\logic\DriverLogic;
use app\inter\logic\OrderLogic;
use app\inter\logic\UserLogic;
use app\admin\inter_logic\DriverLogic as InterDriverLogic;
use my\Address;
use my\Security;
use think\Cache;
use think\Db;
use think\Validate;
use my\Tools;

class InterRefund extends Base
{
    protected $column = array(
        'refund_sn'=>'退款编号',
        'order_sn'=>'订单号',
        'user_phone'=>'申请人',
        'refund_time'=>'退款申请时间',
        'refund_money'=>'申请退款金额',
        'cancel_reason'=>'取消原因',
        'paytool'=>'支付方式',
        'order_price'=>'订单价格',
        'coupon_price'=>'优惠金额',
        'need_price'=>'实际支付金额',
        'user_money'=>'余额支付金额',
        'award_money'=>'赠送余额支付金额',
        'third_price'=>'第三方支付金额',
        'is_handle'=>'是否处理',
        'handle_time'=>'退款成功时间',
//        'price_rate'=>'退款收费比率',
        'force_cancel_rate'=>'强制取消时收费费率',
        'fact_money'=>'实际退款金额',
        'wallet_refund'=>'返回到余额的金额',
        'third_refund'=>'退回到第三方的金额',
        'remark'=>'说明',
    );
    protected $map = array();
    public function _initialize()
    {
        parent::_initialize(); // TODO: Change the autogenerated stub
        $base_condition = $this->base_condition;
        $base_condition&&$this->map['start_code'] = $base_condition['region_code'];
    }
	//退款列表
	public function index(){
        /*$data=config();
        echo "<pre>";
        print_r($data);
        exit;*/
        $config['url'] = url('inter_refund/table');
        $config['order_status'] = inter_order_status();
        $config['pay_type'] = pay_type();
        $this->assign($config);
        return view();
	}

	public function table()
    {
        $page = input('get.page');
        $limit = input('get.limit');
        $refund_logic = new RefundLogic();
        $field = 'a.*,c.order_sn,c.paytool,c.user_money,c.award_money,c.member_id,d.user_phone,e.log_id';
        $res = $refund_logic->getRefund($this->map, $field,$page, $limit);
        $count = $refund_logic->getRefundCount($this->map);

        $res = decode_array_inter_2($res);

        foreach ($res as $key =>$val){
            $res[$key]['user_phone'] = Security::decrypt($val['user_phone']);
        }
        echo json_encode(array(
            'code' => 0,
            'msg' => '',
            'count' => $count,
            'data' => $res
        ));
    }

    //退款申请详情页面
    public function detail()
    {
        $id = input('get.id');
        $config['type'] = input('get.type')=='refund'?'refund':'detail';
        $refund_logic = new RefundLogic();
        $field = 'a.*,order_sn,order_price,coupon_price,need_price,user_money,award_money,third_price,paytool,cancel_reason,d.user_phone,e.log_id';
        $info = $refund_logic->getRefundById($id,$field);
        if($info){
            $user_wallet_info = Db::name('user_wallet')->where('uid',$info['member_id'])->field('wallet_money,return_money')->find();
            $user_wallet_info['wallet_money'] = sprintf("%.2f",$user_wallet_info['wallet_money']/100);
            $user_wallet_info['return_money'] = sprintf("%.2f",$user_wallet_info['return_money']/100);
            $info['user_phone'] = Security::decrypt($info['user_phone']);
            $info['fact_money_c'] = (($info['need_price']*100)- ($info['order_price']*100)*$info['force_cancel_rate']/100)/100;
            $info = decode_array_inter($info);
            $config['fields'] = $this->column;
            $config['info'] = $info;
            $config['user_wallet_info'] = $user_wallet_info;
            $this->assign($config);
            return view();
        }
    }

	//搜索
    public function search()
    {
        $page = input('get.page');
        $limit = input('get.limit');
        $start = strtotime(input('get.start'));
        $end = strtotime(input('get.end'));
        $order_sn = trim(input('get.order_sn'),' ');
        $is_handle = input('get.is_handle');
        $phone = trim(input('get.user_phone'),' ');
        $pay_type = input('get.pay_type');
        $map = $this->map;
        input('get.start')&&$map['refund_time'] = array('egt',$start);
        input('get.end')&&$map['refund_time'] = array('elt',$end);
        input('get.start')&&input('get.end')&&$map['refund_time'] = array('between',array($start,$end));
        $order_sn&&$map['order_sn']=$order_sn;
        $is_handle&&$map['is_handle']=$is_handle;
        $pay_type&&$map['paytool']=$pay_type;
        $phone&&$map['user_phone']=Security::encrypt($phone);
        $refund_logic = new RefundLogic();
        $field = 'a.*,c.order_sn,c.paytool,c.user_money,c.award_money,c.member_id,d.user_phone,e.log_id';
        $res = $refund_logic->getRefund($map, $field,$page, $limit);
        $count = $refund_logic->getRefundCount($map);
        $res = decode_array_inter_2($res);
        foreach ($res as $key =>$val){
            $res[$key]['user_phone'] = Security::decrypt($val['user_phone']);
        }
        echo json_encode(array(
            'code' => 0,
            'msg' => '',
            'count' => $count,
            'data' => $res
        ));
    }

    //退款
    public function refund()
    {
        $data_post = (input('post.'));
        $rule = array(
            'id'=>'require',
            'fact_money'=>'number',
            'type'=>'in:1,2',//1是财务指定，2是自动计算
        );
        $msg = array(
            'id'=>'参数异常',
            'fact_money'=>'退款格式错误',
            'type'=>'处理方式参数错误',
        );
        $config['status'] = 0;
        $validate = new Validate($rule,$msg);
        if(!$validate->check($data_post)){
            $config['msg'] = $validate->getError();
            return log_json($config,'处理城际订单退款结果','InterRefund@refund');
        }
        $refund_logic = new RefundLogic();
//        $field = 'a.*,b.price_rate,b.free_time,order_sn,order_price,need_price,user_money,third_price,paytool,start_time,coupon_id';
        $field = 'a.*,order_sn,order_price,need_price,user_money,award_money,third_price,paytool,start_time,coupon_id';
        $info = $refund_logic->getRefundById($data_post['id'],$field);

        if($info['is_handle']==1){
            $config['msg'] = '该申请已处理，请勿重复操作';
            return log_json($config,'处理城际订单退款结果','InterRefund@refund');
        }
        if(($data_post['fact_money']*100) > ($info['need_price']*100)){
            $config['status'] = 2;
            $config['msg'] = "实际退款金额不应该高于用户实际支付金额";
            $config['data'] = $data_post['fact_c'];
            return log_json($config,'处理城际订单退款结果','InterRefund@refund');
        }
        $info['remark_p'] = $data_post['remark']."<br>";
        //由财务指定退款的金额
        if($data_post['type']==1){
            $info['fact_money_hand'] = (int)$data_post['fact_money'];
            $res = $refund_logic->appointRefund($info);
        }
        //自动计算退款
        else{
            $res = $refund_logic->autoRefund($info);
        }
        $config['msg'] = $res['msg'];
        if($res['status']==1){
            $config['status'] = 1;
            $config['msg'] = '退款成功';
            $config['url'] = url('detail',array('id'=>$data_post['id']));
        }
        return log_json($config,'处理城际订单退款结果','InterRefund@refund');
    }

    //判读司机有无被分配订单并改变司机状态
    protected function dealDriverStatus($did)
    {
        $order_logic = new OrderLogic();
        $map['driver_id'] = $did;
        $map['order_status'] = 35;//已分配
        $common_id_arr = $order_logic->getOrderCommon($map,'id');
        $order_count = 0;
        foreach ($common_id_arr as $value){
            $order_count += $order_logic->orderCountByCommonId($value['id']);
        }
        if(!$order_count){
            $driver_logic = new DriverLogic();
            $driver_logic->renewDriver(array('id'=>$did),array('is_goon'=>2));
        }
    }

    /**
     * 变更订单司机关系的缓存
     * @param $did //司机id
     * @param $common_id //订单id
     * @param $type //1为增加，2为删除
     * */
    protected function changeOrderDriverCache($did,$common_id,$type=1)
    {
        $order_driver_cache = Cache::connect(config('inter_cache'))->get('order_driver_' . $did);
        switch ($type){
            //增加
            case 1:
                $relation = array($common_id=>35);//司机派单
                if($order_driver_cache){
                    $relation = $relation + $order_driver_cache;
                }
                break;
            //取消派单
            case 2:
                if($order_driver_cache){
                    unset($order_driver_cache[$common_id]);
                    $relation = $order_driver_cache;
                }
                break;
        }
        empty($relation)?Cache::connect(config('inter_cache'))->rm('order_driver_' . $did):
            Cache::connect(config('inter_cache'))->set('order_driver_' . $did,$relation,0);
    }

    //退款查询
    public function query()
    {
        if(!empty(input('post.order_sn'))){
            $map = $this->map;
            $map['order_sn'] = trim(input('post.order_sn'));
            $order_logic = new OrderLogic();
            $order_common = $order_logic->getOrderCommon($map, 'a.*',false);
            if(empty($order_common)){
                return json(array('status'=>0,'msg'=>'该订单不存在'));
            }
            if(!in_array($order_common['order_status'],array(20,25))){
                return json(array('status'=>0,'msg'=>'该订单没有退款请求'));
            }
            $refund_logic = new RefundLogic();
            $res = $refund_logic->refundQuery($order_common);
//            dump($res);exit;
            if(empty($res['status'])){
                return json(array('status'=>0,'msg'=>$res['msg']));
            }
            $str = $this->field($order_common['paytool'],$res['data']);
            return json(array('status'=>1,'data'=>$str));
        }
        return view();
    }

    protected function field($key,$data)
    {
        $fields[1] = $fields[2] = $fields[3] = $fields[4] = $fields[5] = array(
            'fact_money' => '实际退款(元)',
            'handle_time' => '退款时间',
            'wallet_refund' => '退回余额的金额(元)',
            'third_refund' => '退款第三方的金额(元)',
            'poundage' => '退款收费金额(元)',
            'paytool' => '支付方式',
        );
        $fields[1] = $fields[4] = array_merge(array('order_sn' => '订单编号', 'third_price' => '第三方交易金额(元)', 'refund_amount' => '第三方退款金额(元)', 'refund_time' => '第三方退款时间'), $fields[1]);
        $fields[2] = $fields[5] = array_merge(array('order_sn' => '订单编号', 'third_price' => '第三方交易金额(元)', 'refund_fee' => '第三方退款金额(元)'), $fields[2]);
        $fields[3] = array_merge(array('order_sn' => '订单编号', 'need_price' => '余额交易金额(元)', 'refund_money' => '余额退款金额(元)'), $fields[3]);
        $str = "<thead><tr>";$str1='<tbody><tr>';
        foreach ($fields[$key] as $i => $v){
            $str .= "<th lay-data=\"{field:'$i', width=120}\">$v</th>";
            switch ($i){
                case 'paytool':
                    $paytool = pay_type()[$data[$i]];
                    $str1 .= "<th>$paytool</th>";
                    break;
                case 'handle_time':
                    $date = date('Y-m-d H:i:d',$data[$i]);
                    $str1 .= "<th>$date</th>";
                    break;
                case 'refund_time':
                    $date = date('Y-m-d H:i:d',$data[$i]);
                    $str1 .= "<th>$date</th>";
                    break;
                case 'refund_amount':
                    $dollar = $data[$i]?:'0.00';
                    $str1 .= "<th>$dollar</th>";
                    break;
                default:
                    $str1 .= "<th>{$data[$i]}</th>";
                    break;
            }
        }
        $str .= "</tr></thead>";
        $str1 .= "</tr></tbody>";
        return $str.$str1;
    }

    //退款------退款逻辑重新更改----20180910
    public function refundScrap()
    {
        $data_post = (input('post.'));
        $config['status'] = 0;
        if(empty($data_post['id'])){
            $config['msg'] = '缺少退款申请记录id参数';
            $this->adminLog('InterRefund@refund',$data_post,'处理城际订单退款结果----缺少退款申请记录id参数');
            return json($config);
        }
        $refund_logic = new RefundLogic();
        $field = 'a.*,order_sn,order_status,order_price,need_price,user_money,third_price,paytool,start_time,coupon_id';
        $info = $refund_logic->getRefundById($data_post['id'],$field);
        if($info['is_handle']!=20){
            $config['msg'] = '退款申请对应的订单状态错误';
            $this->adminLog('InterRefund@refund',$data_post,'处理城际订单退款结果----退款申请对应的订单状态错误');
            return json($config);
        }
        if($info['is_handle']==1){
            $config['msg'] = '该申请已处理，请勿重复操作';
            $this->adminLog('InterRefund@refund',$data_post,'处理城际订单退款结果----该申请已处理，请勿重复操作');
            return json($config);
        }
        $res = $refund_logic->handleRefundScrap($info);
        $this->adminLog('InterRefund@refund',$data_post,"处理城际订单退款结果----{$res['msg']}");
        return json($res);
    }

    //导出数据
    public function excel()
    {
        $all = input('get.all');
        $page = input('get.page') ?: 1;
        $limit = $all == 1 ? 1000 : input('get.limit');

        $map = $this->dealInput(input('get.'));
//        var_dump($map);exit();
        $refund_logic = new RefundLogic();
        $field = 'a.*,c.order_sn,c.paytool,c.user_money,c.award_money,c.member_id,d.user_phone,e.log_id';
        $res = $refund_logic->getRefund($map,$field,$page, $limit);

        $res = decode_array_inter_2($res);
        foreach ($res as $key =>$val){
            $res[$key]['user_phone'] = Security::decrypt($val['user_phone']);
            $res[$key]['is_handle'] = $val['is_handle'] == 1?'已退款':'未退款';
        }

        $header = [
            'id' => 'ID',
            'refund_sn' => '退款编号',
            'refund_money' => '申请退款金额',
            'member_id' => '用户',
            'user_phone' => '用户手机号',
            'common_id' => '订单ID',
            'order_sn' => '订单号',
            'paytool' => '支付方式',
            'refund_time' => '申请退款时间',
            'is_handle' => '是否退款',
            'handle_time' => '退款成功时间',
            'fact_money' => '实际退款金额',
            'wallet_refund' => '返回余额金额',
            'third_refund' => '退回到第三方的金额',
            'poundage' => '退款手续费',
            'remark' => '备注',
        ];

        $data = [];
        foreach ($res as $key => $value) {
            foreach ($header as $k => $v) {
                $data[$key][$v] = $value[$k];
            }
        }
        Tools::excelExport('城际退款订单', $header, $data);
    }

    public function dealInput($data) {
        $start = strtotime($data['start']);
        $end = strtotime($data['end']);
        $order_sn = trim($data['order_sn'],' ');
        $is_handle = $data['is_handle'];
        $phone = trim($data['user_phone'],' ');
        $pay_type = $data['paytool'];

        $map = [];
        input('get.start')&&$map['refund_time'] = array('egt',$start);
        input('get.end')&&$map['refund_time'] = array('elt',$end);
        input('get.start')&&input('get.end')&&$map['refund_time'] = array('between',array($start,$end));
        $order_sn&&$map['order_sn'] = $order_sn;
        $is_handle&&$map['is_handle'] = $is_handle;
        $pay_type&&$map['paytool'] = $pay_type;
        $phone&&$map['user_phone'] = Security::encrypt($phone);

        return $map;
    }
}